package com.example.shiyan3.others;

import com.example.shiyan3.pojo.VirusDate;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;


/**
 * @Auther: Graycat
 * @Date: 2020/5/8 13:07
 * Create by lwj.
 */
@Configuration
@EnableScheduling
public class GetDate {

    final static String DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    public final static List<VirusDate> confirmedList = new ArrayList<>();

    public void getVirusDate() throws IOException {
        changeIntoList(fetchVirusDate(DATA_URL));
    }

    @Scheduled(cron = "${lwj.Schedules.updateVirusDateCron}")
    public void scheduledGetDate() throws IOException {
        changeIntoList(fetchVirusDate(DATA_URL));
    }


    //爬取csv文件
    public Resource fetchVirusDate( String url ){
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(url))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();
        return body;
    }

    //转换csv文件到List中
    public void changeIntoList( Resource body ) throws IOException {
        if ( body!=null ) {
            final Reader reader = new InputStreamReader(body.getInputStream());
            final CSVParser pasre = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
            for ( CSVRecord record : pasre) {
                confirmedList.add(VirusDate.builder()
                        .province(record.get(0))
                        .country(record.get(1))
                        .longitude(Double.parseDouble(record.get(2)))
                        .latitude(Double.parseDouble(record.get(3)))
                        .latestTotal(Integer.parseInt(record.get(record.size()-1)))
                        .raise( (Integer.parseInt(record.get(record.size()-1))) - (Integer.parseInt(record.get(record.size()-2))))
                        .build());
            }
            reader.close();
        }
    }


}
